package com.banggood.upms.converter;

import com.banggood.upms.bean.po.TreePermission;
import com.banggood.upms.bean.vo.TreePermissionVo;
import com.banggood.upms.common.component.CommonComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XuChuangFeng
 * @date 2017/7/25
 */
@Component
public class TreePermConverter {

    @Autowired
    private CommonComponent component;

    /**
     * #1，将数据库中的树跟权限的映射关系转换成Map集合
     * #2，判断前端传入的当前元素是否已经存在于数据库中（Map集合），若已存在则将这个元素从map中剔除，不存在则证明这个元素是要添加的，map中剩下的元素就是要删除的
     * @param vo 前端传入的，可以获取到最终调整之后的元素
     * @param preAdjustTreePerms DB中获取的，未调整之前的元素集合
     * @param treePermIdsForRemove 这次调整将要删除的upms_tree_permission表中的主键
     * @param treePermListForInsert 这次调整将要添加的元素集合
     * @return
     */
    public void prepareAdjustElements(TreePermissionVo vo,
                                      List<TreePermission> preAdjustTreePerms, List<String> treePermIdsForRemove, List<TreePermission> treePermListForInsert) {
        Map<String, TreePermission> preAdjustTreePermMap = transferToMap(preAdjustTreePerms);
        for(String permissionId : vo.getNewPermIds()) {
            // #1,若这个树的ID已经存在于调整前的集合中，证明这个元素已经是添加过的，不需要做调整
            if(preAdjustTreePermMap.containsKey(permissionId)) {
                preAdjustTreePermMap.remove(permissionId);
            } else {
                treePermListForInsert.add(preparePO(permissionId, vo.getTreeId()));
            }
        }
        extractUserTreeIdsForRemove(preAdjustTreePermMap, treePermIdsForRemove);
    }

    //将List转化为以permissionId为Key，以TreePermission为value的Map
    public Map<String, TreePermission> transferToMap(List<TreePermission> pos) {
        Map<String, TreePermission> preAdjustTreePermMap = new HashMap<>();
        for(TreePermission po : pos) {
            preAdjustTreePermMap.put(po.getPermissionId(), po);
        }
        return preAdjustTreePermMap;
    }

    private void extractUserTreeIdsForRemove(Map<String, TreePermission> preAdjustUserTreeMap, List<String> userTreeIdsForRemove) {
        for(String id : preAdjustUserTreeMap.keySet()) {
            userTreeIdsForRemove.add(preAdjustUserTreeMap.get(id).getTreePermissionId());

        }
    }

    public List<TreePermission> transferToPersistentList(TreePermissionVo vo) {
        List<TreePermission> pos = new ArrayList<>();
        for(String id : vo.getNewPermIds()) {
            pos.add(preparePO(id, vo.getTreeId()));
        }
        return pos;
    }

    private TreePermission preparePO(String permissionId, String treeId) {
        TreePermission po = new TreePermission();
        po.setTreeId(treeId);
        po.setPermissionId(permissionId);
        po.setTreePermissionId(component.generateId());
        return po;
    }
}
